import {
  Injectable,
  NestInterceptor,
  ExecutionContext,
  CallHandler,
} from "@nestjs/common";
import { Observable } from "rxjs";
import { tap } from "rxjs/operators";
import { Repository } from "typeorm";

/**
 * 时间戳拦截器
 * 自动为实体设置创建时间和更新时间
 */
@Injectable()
export class TimestampInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const request = context.switchToHttp().getRequest();
    const { body } = request;

    // 在请求处理前设置时间戳
    if (body && typeof body === "object") {
      this.setTimestamps(body, request.method);
    }

    return next.handle().pipe(
      tap((data) => {
        // 在响应返回后可以做一些处理
        if (data && typeof data === "object") {
          this.setTimestamps(data, request.method);
        }
      })
    );
  }

  private setTimestamps(entity: any, method: string): void {
    if (!entity || typeof entity !== "object") {
      return;
    }

    const now = new Date();

    // 处理单个实体
    if (entity.created_at !== undefined || entity.updated_at !== undefined) {
      if (
        method === "POST" &&
        (entity.created_at === null || entity.created_at === undefined)
      ) {
        entity.created_at = now;
      }
      if (method === "PUT" || method === "PATCH") {
        entity.updated_at = now;
      }
    }

    // 处理数组中的实体
    if (Array.isArray(entity)) {
      entity.forEach((item) => this.setTimestamps(item, method));
    }

    // 处理嵌套对象
    Object.keys(entity).forEach((key) => {
      if (
        entity[key] &&
        typeof entity[key] === "object" &&
        !Array.isArray(entity[key])
      ) {
        this.setTimestamps(entity[key], method);
      }
    });
  }
}
